const http = require('http')
const fs   = require('fs')
const url  = require('url')
const path = require('path')

const server = http.createServer((req, res) => {
	if (req.url === '/favicon.ico') {
		return
	}
	// url = http://127.0.0.1:80/guaguaerhao/test.html
	// url.parse(req.url).pathname === /guaguaerhao/test.html
	let pathname = url.parse(req.url).pathname

	if (pathname.indexOf('.') === -1) {
		pathname += '/index.html'
	}
	const fileUrl = './' + path.normalize('./static/' + pathname)

	const ext = path.extname(pathname)
	fs.readFile(fileUrl, (err, data) => {
		if (err) {
			res.writeHead(404, {'Content-Type': 'text/html;charset=UTF-8'})
			res.end('404，頁面沒有找到')
		}
		getMime(ext, mime => {
			res.writeHead(200, {'Content-Type': mime})
			res.end(data)
		})
	})
})

server.listen(80, '127.0.0.1', () => {
	console.log('127.0.0.1:80 running')
})

function getMime(extname, callback) {
	fs.readFile('./mime.json', (err, data) => {
		if (err) {
			throw Error('找不到mime.json文件')
			return
		}
		//转成JSON
        const mimeJSON = JSON.parse(data);
        const mime =  mimeJSON[extname]  || "text/plain";
        //执行回调函数，mime类型字符串，就是它的参数
        callback(mime);
	})
}